package online.heycm.platform.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import java.util.Properties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * 配置监听/推送自动装配
 *
 * @author heycm
 * @since 2023/11/8 19:17
 */
@Configuration
@EnableConfigurationProperties({NacosProperties.class, BaseNacosConf.class})
public class NacosAutoConfiguration {

    /**
     * 注册 NacosConfigService 实例
     *
     * @param nacosProperties Nacos配置参数
     * @return NacosConfigService
     * @throws NacosException
     */
    @Bean
    @ConditionalOnMissingBean(value = {ConfigService.class})
    public ConfigService configService(NacosProperties nacosProperties) throws NacosException {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosProperties.getServerAddr());
        properties.put(PropertyKeyConst.NAMESPACE, nacosProperties.getNamespace());
        if (!StringUtils.isEmpty(nacosProperties.getUsername()) && !StringUtils.isEmpty(
                nacosProperties.getPassword())) {
            properties.put(PropertyKeyConst.USERNAME, nacosProperties.getUsername());
            properties.put(PropertyKeyConst.PASSWORD, nacosProperties.getPassword());
        }
        return NacosFactory.createConfigService(properties);
    }

    /**
     * 注册 NacosConfListener 监听器实例
     *
     * @param nacosProperties Nacos配置参数
     * @param configService   NacosConfigService 实例
     * @return NacosConfListener
     */
    @Bean
    @ConditionalOnMissingBean(value = {NacosConfListener.class})
    public NacosConfListener nacosConfListener(NacosProperties nacosProperties, ConfigService configService) {
        return new NacosConfListenerImpl(nacosProperties, configService);
    }

    /**
     * 注册 NacosConfPublisher 推送器实例
     *
     * @param nacosProperties Nacos配置参数
     * @param configService   NacosConfigService 实例
     * @return NacosConfPublisher
     */
    @Bean
    @ConditionalOnMissingBean(value = {NacosConfPublisher.class})
    public NacosConfPublisher nacosConfPublisher(NacosProperties nacosProperties, ConfigService configService) {
        return new NacosConfPublisherImpl(nacosProperties, configService);
    }

}
